define(["../common"], function() {
	
	// 重发邮件剩余时间
	var remainTime = 0;
	var timeIndex = -1;
	
	var pwdFormCfg = {
		fields: {
			pwd: "密码:required"
		}	
	};	
	var bindFormCfg = {
		fields: {
			email: "邮箱地址:required;email",
			captcha: "验证码:required;digits;length[~6]"
		}
	};
	
	// 防止自动填充
	$("input").val("");
	
	requirePlugin(["validator"],function() {
		$("#step_0").validator(pwdFormCfg);
		$("#step_1").validator(bindFormCfg);
	});
	
	// 获取绑定进度信息(包括步骤进度,0短信发送或者1邮件发送)
	$.getJSON(g_userDomain + "/member/stepInfo/json?r" + Math.random(), {type: 1}, function(data) {
		
		// 显示表单
		if (!data.result.isVerified) {
			$("#step_0").show();
			$(".step:eq(0)").addClass("active");
			$("#pwd").val("").focus();
		} else {
			$("#step_1").show();
			$(".step:lt(2)").addClass("active");
			$("#email").focus();
		}
		
		// 倒计时
		remainTime = parseInt(data.result.remainTime/1000);
		if (remainTime < 0) {
			remainTime = 0;
		}
		setTime();
	});

	// 密码
	$("#step_0").on('valid.form', function(e, form){
		var $form = $(form);
		if (!$form.lock()) return;
		
		$form.loadMsg("正在验证...");
		$.post(g_userDomain + "/member/verifyPwdDo/json", $form.serialize(), function(data) {
			if (data.status !== 0) {
				$form.failMsg(data.message);
				 return;
			}
			$form.hideMsg();
			
			$("[id^=step_]").hide();
			$("#step_1").show();
			$(".step:eq(1)").addClass("active");
			$("#email").focus();
		});
		
	});
	
	// 事件：获取验证码
	$("#btn_send").click(function() {
		var $this = $(this);
		if (remainTime > 0 || !$this.lock()) {
			return;
		}
		var $email = $("#email");
		if (!$email.isValid()) {
			$this.failMsg("请输入有效邮箱地址");
		}
		$this.loadMsg("发送邮件...");
		$.post(g_userDomain + "/member/sendEmail/json", {email: $email.val()}, function(data) {
			if (data.status != 0) {
				$this.failMsg(data.message);
				setTime();
				return;
			}
			$this.hideMsg();
			
			// 重发倒计时
			remainTime = parseInt(data.result/1000);
			setTime();
		});
	});
	
	// 绑定
	$("#step_1").on('valid.form', function(e, form){
		var $form = $(form);
		if (!$form.lock()) return;
		
		$form.loadMsg("正在绑定...");
		$.post(g_userDomain + "/member/emailDo/json", $form.serialize(), function(data){
			if (data.status !== 0) {
				$bindForm.failMsg(data.message);
				return;
			}
			$form.infoMsg("绑定成功");
			
			$("[id^=step_]").hide();
			$("#step_2").show();
			$(".step:eq(2)").addClass("active");
		});
	});
	
	// 倒计时
	function setTime() {
		clearTimeout(timeIndex);
		if (remainTime == 0) {
			$("#btn_send").removeClass("disabled").html("获取验证码");
			return;
		}
		$("#btn_send").addClass("disabled").html(remainTime);
		remainTime--;
		timeIndex = setTimeout(function() {
			setTime();
		}, 1000);
	}
});